// STM32F100 and SI4032 RTTY transmitter
// released under GPL v.2 by anonymous developer
// enjoy and have a nice day
// ver 1.5a

#include <stm32f10x_gpio.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <misc.h>

#include "config.h"
#include "delay.h"
#include "init.h"
#include "dht.h"
#include "radio.h"
#include "morse.h"


#define GREEN GPIO_Pin_7	// Inverted
#define RED   GPIO_Pin_8

float tx_freq = TRANSMIT_FREQUENCY;

void morse_beacon (void);


int main (void)
{
  RCC_Conf();
  init_port();
  delay_init();

  GPIO_ResetBits (GPIOB, RED);
  GPIO_SetBits (GPIOB, GREEN);	// NOTE - Green LED is inverted

  radio_soft_reset();
  radio_set_tx_frequency (tx_freq); // setting TX frequency
  radio_rw_register (0x6D, 00 | (TX_POWER & 0x0007), 1); // setting power
  radio_rw_register (0x71, 0x00, 1); // initial RTTY modulation
  radio_rw_register (0x13, 0x00, 1); // Was 0xF0(?) Temperature Value Offset
  radio_rw_register (0x12, 0x20, 1); // Temperature Sensor Calibration

  // SPI needs a beating first to start working
  _delay_ms (250);		// found this needed on battery --cjb
  spi_init();
  radio_set_tx_frequency (tx_freq);
  radio_rw_register (0x71, 0x00, 1);

  //

  radio_enable_tx();
  _delay_ms (250);
  radio_disable_tx();

  while (1)
    if (collect_weather_data())
      morse_beacon ();
    else
      _delay_ms (5000);
}


const char* info[] =
  {
   "LOC QF57PC",
   "PWR 20 DBM",
   "RIG RS41",
   "BUILD HIGH FOR HAPPINESS",
   "MY DOG CHEWED MY FEEDLINE",
   "SO I HAD TO GROUND HIM",
   0
  };


void morse_beacon (void)
{
  static char** inf = (char**)info;
  static int pass = 7;
  char buf[200];
  int delay = 60000;

  buf[0] = 0;

  if (++pass > 7)
    {
      sprintf (buf, "DE VK2CJB WX BEACON %s +", *inf);
      if (*++inf == 0) inf = (char**)info;
      pass = 0;
      delay = 5000;
    }
  else
    sprintf (buf, "%c %02d%01d H %02d +",
	     (dht_data[2] < 0 ? 'N' : 'T'),
	     dht_data[2], dht_data[3], dht_data[0]);

  if (buf[0]) send_morse (buf);

  _delay_ms (delay);
}
